<!--执行中-->
<template>
  <div class="bg">

    <!-- 类型 -->
    <SubMenuOval v-if="menuz" class="menu" :menus="menuz" :menu="menu" :max="false" @menuClick="menuClick"></SubMenuOval>
    
    <!-- 列表 -->
    <list class="list">
      <refresh class="refresh" @refresh="httpStrategys" :display="isRefresh ? 'show' : 'hide'">
        <loading-indicator class="load text1"></loading-indicator>
      </refresh>

      <cell v-for="(item, index) in datas" v-bind:key="index">

        <div class="list_bg" v-if="item != ''">
          <VRunTrust v-if="item.executeType == undefined" class="cell" :item="item"></VRunTrust>
          <VRunStock v-else-if="item.isContract == 'spot'" class="cell" :item="item"></VRunStock>
          <VRunContract v-else class="cell" :item="item"></VRunContract>
        </div>

        <div class="genduo-bg" v-else>
          <text class="font22 text3">{{T('没有更多数据')}}</text>
        </div>
      </cell>
    </list>
  </div>
</template>

<script>


//组件
import SubMenuOval from '@/public/view/SubMenuOval.vue'
import VRunContract from '@/run/view/VRunContract.vue' 
import VRunStock from '@/run/view/VRunStock.vue'
import VRunTrust from '@/run/view/VRunTrust.vue'

//功能
import modal from "@/_js/modal";
import math from "@/_js/math";
import Config from "@/_js/config";
import broadcast from "@/_js/broadcast";

import amRunMqtt from "@/run/amRunMqtt";

import weexHttp from "@/_js/https"; ;
const WeexMqtt = weex.requireModule("WeexMqtt");
const weexFunction = weex.requireModule('WeexFunction');

import I18N from "@/_i18n/i18n";
var T = I18N.t;

export default {

  components: {
    SubMenuOval,
    VRunContract,
    VRunStock,
    VRunTrust,
  },

  data() {
    return {
      T:T,
      Config:Config,
      math:math,
      isAppear:false, //turn 完全显示-解决界面未显示但是刷新数据后订阅消息问题
      isRefresh:false, //turn 刷新

      menus:undefined, //分类数组-不带数量
      menuz:undefined, //分类数组-带数量
      menu:0, //当前选中分类
      datad:undefined, //执行列表-分类表
      dataAll:undefined, //执行列表-所有
      datas:[], //执行列表-当前分类
      
      newMasgs:{}, //MQTT新消息
    };
  },

  //移除时触发
  destroyed(){
    this.viewdisappear();
  },

  mounted() {

    this.isAppear = true;
    this.httpStrategys();
    this.upData();

    //刷新订阅
    broadcast.subscribe('Run', broadcast.EXECUTE_UPDATE, ()=>{
      this.httpStrategys();
    });
  },
  
  methods: {

    //初始化数据
    initDatas(datas) {

      for (let index = 0; index < datas.length; index++) {
        var map = datas[index];
        
        //托管
        if (map.executeType == undefined) {
          var length = math.getCoin(map.investCoin);
          map.investCoinNum = math.xiaoshu(map.investCoinNum, length, 2); 
          continue;
        }

        //PUBLIC表示共享,PRIVATE表示私有,MEMBER表示购买会员赠送的
        //服务器名称
        var serverName = T('公共服务器');
        if (map.serverType) {
          serverName = map.serverMark ? map.serverMark : map.serverCode;
          var name = map.serverType == 'PRIVATE' ? T('独享') : T('共享');
          serverName = name + '#' + serverName;
        }
        map.serverName = serverName;
        
        //投资币数量
        var length = math.getCoin(map.investCoin);
        map.investCoinnNum = math.xiaoshu(map.investCoinnNum, length, 2); 

        //总盈亏
        map.realEarnings = math.xiaoshu(map.realEarnings, length, 2);
        map.realEarningsRate = math.xiaoshu(map.realEarningsRate, 2, 2);

        //浮动盈亏
        map.floatEarnings = math.xiaoshu(map.floatEarnings, length, 2);
        map.floatEarningsRate = math.xiaoshu(map.floatEarningsRate, 2, 2);

        //实现盈亏
        map.earnings = math.xiaoshu(map.earnings, length, 2);
        map.earningsRate = math.xiaoshu(map.earningsRate, 2, 2);

        //实现年化
        map.yearIncome = math.xiaoshu(map.yearIncome, 2, 2);
        map.realYearIncome = math.xiaoshu(map.realYearIncome, 2, 2);

        //下面是 初始化 合约数据
        if (map.isContract == 'spot') {
          continue;
        }

        //担保资产率
        map.riskRate = math.cheng(map.riskRate, "100", 2, 2);

        //策略方向
        var pair = map.config.tradePairs[0];
        var investType = pair.investType + '';
        switch (investType) {
          case '0': 
            map.contract_num = 1;
            map.contract_show = T('做多') + pair.leverRate + 'X';
            break;
          case '1':
            map.contract_num = -1;
            map.contract_show = T('做空') + pair.leverRate + 'X';
            break;
          default:
            map.contract_num = 0;
            map.contract_show = T('双向') + pair.leverRate + 'X';
            break;
        }
      }

      return datas;
    }, 
    
    /** executeType
     * OFFICIAL 平台-单币对
     * FATHER 平台-多币对
     * PRIVATE 私有
     * BUY 商城
     */

    /** isContract
     * spot 现货
     * contract_usdt U本位合约
     */

    /** isFollow
     * true 跟单
     */
    //初始化分类
    initMenu(datas){

      //数据分类
      var datad = {};
      var addData = (name, data)=>{
        if (datad[name] == undefined) {
          datad[name] = [];
        }
        var array = datad[name];
        array.push(data);
      };

      //菜单统计
      var menus = [T('全部')]; //菜单数组
      var menud = {};
      var addMenu = (name)=>{
        if (menud[name] == undefined) {
          menus.push(name);
        }
        var num = menud[name];
        menud[name] = num ? (num + 1) : 1;

        num = menud[T('全部')];
        menud[T('全部')] = num ? (num + 1) : 1;
      }
      
      //循环分类
      for (let index = 0; index < datas.length; index++) {

        var data = datas[index];

        //托管
        if (data.executeType == undefined) {
          addData(T('量化托管'), data);
          addMenu(T('量化托管'));
          continue;
        }

        //跟单
        if (data.isFollow) {
          addData(T('跟单'), data);
          addMenu(T('跟单'));
          continue;
        }

        //私有
        if (data.executeType == 'PRIVATE') {
          addData(T('私有'), data);
          addMenu(T('私有'));
          continue;
        }
        
        //商城
        if (data.executeType == 'BUY') {
          addData(T('商城'), data);
          addMenu(T('商城'));
          continue;
        }

        //平台-币币
        if (data.isContract == 'spot') {
          addData(T('平台币币'), data);
          addMenu(T('平台币币'));
          continue;
        }

        //平台-合约
        if (data.isContract == 'contract_usdt') {
          addData(T('平台合约'), data);
          addMenu(T('平台合约'));
          continue;
        }
      }

      //菜单-不带数量
      this.menus = menus;
      this.menu = this.menu < menus.length ? this.menu : 0;
      
      //菜单-带数量
      var menuz = [];
      for (let index = 0; index < menus.length; index++) {
        var name = menus[index];
        var num = menud[name] ? menud[name] : 0;
        name = name + ' ' + num;
        menuz.push(name);
      }
      this.menuz = menuz;

      //执行列表-分类表
      for (const key in datad) {
        var array = datad[key];
        array.push('');
      }
      this.datad = datad;
    },

    /*********************** 通信触发*/
    //完全显示触发
    viewappear() {
      
      this.isAppear = true;
      WeexMqtt.message((data)=>{

          //交易对订阅信息
          var last = amRunMqtt.getPairMsg(data);
          if (last != undefined) {
            this.newMasgs[data.topic] = last;
          }
          
          //运行订阅信息
          var msg = amRunMqtt.getRunMsg(data);
          if (msg != undefined) {
            this.newMasgs[msg.executeId] = msg;
          }
      });

      amRunMqtt.mqttSubscribes(); //订阅主题
      amRunMqtt.mqttSendMsg(); //mqtt发送消息
    },

    //完全显示隐藏
    viewdisappear() {
      this.isAppear = false;
      amRunMqtt.unSubscribes();
    },

    /********************************** HTTP*/
    //策略列表-刷新
    httpStrategys() {
      
      if (!Config.isLogin || this.isRefresh) return;
      this.isRefresh = true;

      var param = {};
      weexHttp.post("strategyV3/executeList",param,true,(data) => {

          this.isRefresh = false;
          if (data.status == 200) {

            data = data.data;
            var datas = this.initDatas(data.executeList);
            this.initMenu(datas);

            this.dataAll = datas;
            this.dataAll.push('');

            this.menuClick(this.menu);

            amRunMqtt.initMqttRunTopic(datas); //初始订阅主题
            
            //订阅-解决界面未显示但是刷新数据后订阅消息问题
            if (this.isAppear) {
              this.viewappear();
            }
          } else {
            modal.toast(data.msg);
          }
      });
    },

    /*********************** 功能方法*/
    //更新数据-MQTT
    upData() {
      
      // 延迟 递归 更新数据
      var delayedUpData = ()=>{
        setTimeout(() => {
          this.upData();
        }, 1000);
      };

      if (JSON.stringify(this.newMasgs) == '{}') {
        delayedUpData();
        return;
      }

      var newMasgs = JSON.parse(JSON.stringify(this.newMasgs));
      this.newMasgs = {};
      for (let index = 0; index < this.dataAll.length; index++) {

        var map = this.dataAll[index];
        if (map.isContract != 'contract_usdt') { 
          continue;
        }

        //交易对数据
        var pair = map.config.tradePairs[0];
        var topicPair = amRunMqtt.geTopicPair(pair.exchangeName, pair.counterCoin, 'USDT');;
        var last = newMasgs[topicPair];
        if (last != undefined) {
          map.last = last;
        }

        //运行数据
        var newMasg = newMasgs[map.executeId]; //担保资产率
        if (newMasg != undefined) {

          map.marginBalance = newMasg.marginBalance; //账户权益
          map.riskRate = newMasg.riskRate; //担保资产率

          //双向-不更新下面数据---零时处理BUG
          if (map.contract_num != 0) {
            
            map.floatEarnings = newMasg.floatEarnings; //浮动盈亏
            map.floatEarningsRate = newMasg.floatEarningsRate; //浮动盈亏率

            map.realEarnings = math.jia(map.earnings, map.floatEarnings); //总收益
            
            var realEarningsRate = math.chu(map.realEarnings, map.investCoinnNum); //总收益率
            map.realEarningsRate = math.cheng(realEarningsRate, '100', 2, 2);
          }
        }
      }
      
      delayedUpData();
    },

    /********************************** 点击触发*/
    //菜单点击
    menuClick(menu) {

      this.menu = menu;
      var name = this.menus[menu];
      var datas = (name == T('全部')) ? this.dataAll : this.datad[name];
      this.datas = datas;
    },
  },
};

</script>


<style src="@/_css/style.css"></style>
<style scoped>
.bg {
  width: 750px;
  flex: 1;
  z-index: 9;
}

/*********************** 列表*/
.list {
  margin-top: 20px;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 9;
}
.cell {
  width: 710px;
  margin-top: 20px;
  margin-left: 20px;
  margin-bottom: 20px;
}

/*********************** 刷新*/
.refresh {
  width: 750;
  flex-direction: row;
  justify-content: center;
}
.load {
  height: 40px;
  width: 40px;
}
.genduo-bg {
  flex-direction: row;
  justify-content: center;
  align-items: center;
  width: 750px;
  height: 100px;
}

/*********************** 弹出菜单*/
.menu {
  margin-left: 20px;
  margin-right: 20px;
}
</style>